/*
 * Created on 2007-12-9
 *
 * TODO 
 */
package jacky.lanlan.song.pattern.command;

import jacky.lanlan.song.pattern.Composite;

import java.util.ArrayList;
import java.util.List;

/**
 * Command的 <i>Composite模式</i> 实现，包含了多个Command的Command，
 * 当执行时，会一起执行所有复合的Command。
 * @author Jacky.Song
 */
public class CompositeCommand implements Command,Composite<Command> {

	private List<Command> commands=new ArrayList<Command>();
	
	/**
	 * 添加Command。
	 */
	public void addCommand(Command c) {
		this.commands.add(c);
	}
	
	/**
	 * 删除Command。
	 */
	public void removeCommand(Command c) {
		this.commands.remove(c);
	}

	/**
	 * 判断复合Command里面是否包含指定的Command。
	 * @param c 指定Command
	 * @return true如果是，false如果不是
	 */
	public boolean containCommand(Command c) {
		return this.commands.contains(c);
	}
	
	public void execute() throws Exception {
		this.batchExecute(this.commands.toArray(new Command[this.commands.size()]));
	}

	private void batchExecute(Command... commands) throws Exception {
		for (Command command : commands) {
			command.execute();
		}
	}
	
	public Command combine(final Command... parts) {
		return new Command() {
			public void execute() throws Exception {
				batchExecute(parts);
			}
		};
	}

}
